Common Iteration Errors

Infinite Loop Errors

It is important to consider how a loop will end. All loops have a condition expression that must evaluate to false for the loop to end. If the condition never evaluates to false, than an infinite loop will result and the program will never end, and may crash by filling up the program's memory or causing other types of overflow errors. Often, it appears as if the program is doing nothing, when it is really stuck in a loop of repeating the same actions over and over.

Here's an example of an infinite loop:

sum = 0;
count = 10;
while ( count > 0 )
    sum = sum + 10;
end

To fix an infinite loop, add code that changes (updates) something in the conditional expression so that eventually it evaluates to false.

count = 10;
while ( count >= 0 )
    sum = sum + 10;
    count = count - 1;
end

What would happen if the additional line was count = count + 1

Off-by-one Errors

Another important consideration when implementing iterative code, is the number of times that the loop must execute to solve the problem. It is a very common mistake to program a loop that executes one too many times or one too few times. This type of programming error is a semantic error and as such can not be caught by the programming environment's syntax checker. It is the programmer's responsibility to ensure that the body of each loop repeats the correct number of times for all possible cases of entering the loop.

Here's an example of a loop that has an off-by-one error if we wish it to execute 10 times.

sum = 0;
count = 10;
while ( count >= 0 )
    sum = sum + 10;
    count = count - 1;
end

One way to determine if a loop executes the correct number of times is to reduce the count number and trace the execution manually.

sum = 0;
count = 1;
while ( count >= 0 )
    sum = sum + 1;
    count = count - 1;
end

If you don't find the problem this way, then use the Debugging tool to trace the actual code.